package com.yc.dao;

import com.yc.bean.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.util.List;

/**
 * @author zwei
 * @create 2024-08-07 16:19
 */
@Repository // 声明是一个持久层
public class AccountDaoImpl implements AccountDao{
    //         注入数据源
    @Autowired
    private JdbcTemplate jdbcTemplate;
//    @Autowired
//    public void init(DataSource dataSource){
//        this.jdbcTemplate = new JdbcTemplate(dataSource);
//    }
    @Override
    public int insert(double money) {
        String sql="insert into accounts(balance) values(?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        PreparedStatementCreator pc;
        int result=jdbcTemplate.update(connection->{
            PreparedStatement ps=connection.prepareStatement(sql,new String[]{"accountid"});
            ps.setString(1,money+"");
            return ps;
        },keyHolder);
        return keyHolder.getKey().intValue();
    }

    @Override
    public void update(int accountid, double money) {
        String sql="update accounts set balance=? where accountid=?";
        jdbcTemplate.update(sql,money,accountid);
    }

    @Override
    public void delete(int accountid) {
        String sql="delete from accounts where accountid=?";
        jdbcTemplate.update(sql,accountid);
    }

    @Override
    public int findCount() {
        String sql="select count(*) from accounts";
        Integer count=jdbcTemplate.queryForObject(sql,Integer.class);
        return count;
    }

    @Override
    public List<Account> findAll() {
        String sql="select * from accounts";
        List<Account> accounts=jdbcTemplate.query(sql, (rs, rowNum) -> {
            Account account=new Account();
            account.setAccountid(rs.getInt(1));
            account.setBalance(rs.getDouble(2));
            return account;
        });
        if (accounts==null){
            throw new ArithmeticException("未找到该用户");
        }
        return accounts;
    }

    @Override
    public Account findById(int accountid) {
        String sql="select * from accounts where accountid=?";
        Account account=jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
            Account account1=new Account();
            account1.setAccountid(rs.getInt(1));
            account1.setBalance(rs.getDouble(2));
            return account1;
        },accountid);
        if (account==null){
            throw new RuntimeException("未找到该用户");   //TODO: Dao层的异常会被spring转换为DataAccessException
        }
        return account;
    }
}
